package com.gome.ocean.controller.authority;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.Page;
import com.gome.ocean.common.constants.Constants;
import com.gome.ocean.common.exception.UserServiceException;
import com.gome.ocean.common.utils.ResponsePage;
import com.gome.ocean.dao.model.authority.Role;
import com.gome.ocean.dao.model.authority.User;
import com.gome.ocean.dao.model.websql.GUserFrequentlySql;
import com.gome.ocean.service.authority.RoleService;
import com.gome.ocean.service.authority.UserService;
import com.gome.ocean.service.base.BaseController;
import com.gome.ocean.service.websql.SqlHandleService;

/**
 * Created by liuqingxia on 2016/2/25.
 */
@Controller
@RequestMapping("/admin")
public class UserManageController extends BaseController {

    private static final Logger LOG = LoggerFactory.getLogger(UserManageController.class);
    @Autowired
    private UserService         userService;
    @Autowired
    private RoleService         roleService;
    @Autowired
    private SqlHandleService    sqlHandleService;

    @RequestMapping(value = "/user/insert", method = RequestMethod.GET)
    public ModelAndView insertGet(ModelAndView mav) {
        List<Role> list = roleService.getAllRoles();
        mav.addObject("userInsertList", list);
        mav.setViewName("authority/user/insert");
        return mav;
    }

    @RequestMapping(value = "/user/insert", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage insertPost(HttpServletRequest req) {
        ResponsePage page = new ResponsePage();
        User user = new User();
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        String role = req.getParameter("role");
        String telphone = req.getParameter("telphone");
        if (StringUtils.isBlank(email)) {
            return page.setErrorMsg("email不能为空");
        }
        if (!email.matches(Constants.REG_EMAIL)) {
            return page.setErrorMsg("email格式不正确，正确格式为：XXX@gomeplus.com");
        }
        if (StringUtils.isBlank(password)) {
            return page.setErrorMsg("密码不能为空");
        }
        if (password.length() > 10 || password.length() < 6) {
            return page.setErrorMsg("密码长度在6到10位之间，包括6,10");
        }
        if (StringUtils.isBlank(role)) {
            return page.setErrorMsg("角色不能为空");
        }
        if (StringUtils.isBlank(telphone)) {
            return page.setErrorMsg("请输入手机号");
        }
        if (!telphone.matches("1([\\d]{10})")) {
            return page.setErrorMsg("手机号格式不正确");
        }
        String roleId = req.getParameter("roleId");
        user.setRoleId(Long.parseLong(roleId));
        user.setEmail(email);
        user.setPassword(password);
        user.setRole(role);
        user.setTelphone(telphone);
        try {
            if (userService.insertUser(user)) {
                return page.setSuccessMsg("新建用户成功");
            } else {
                return page.setErrorMsg("新建用户失败");
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return page.setErrorMsg("新建用户过程中发生异常，异常信息为：" + e.getMessage());
        }
    }

    @RequestMapping(value = "/user/remove", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage remove(@RequestParam("id") Long id) {
        ResponsePage page = new ResponsePage();
        if (null == id || id <= 0) {
            page.setErrorMsg("id不能为空或0");
        }
        try {
            if (userService.removeUser(id)) {
                return page.setSuccessMsg("删除成功");
            } else {
                return page.setErrorMsg("删除失败");
            }
        } catch (Exception e) {
            return page.setErrorMsg("删除过程中发生异常，异常信息为：" + e.getMessage());
        }
    }

    @RequestMapping(value = "/user/update", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage update(HttpServletRequest req, @RequestParam("id") long id) {
        ResponsePage page = new ResponsePage();
        User user = new User();
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        String role = req.getParameter("role");
        String telphone = req.getParameter("telphone");
        if (StringUtils.isBlank(email)) {
            return page.setErrorMsg("email不能为空");
        }
        if (!email.matches(Constants.REG_EMAIL)) {
            return page.setErrorMsg("email格式不正确，正确格式为：XXX@gomeplus.com");
        }
        if (StringUtils.isBlank(password)) {
            return page.setErrorMsg("密码不能为空");
        }
        if (password.length() > 10 || password.length() < 6) {
            return page.setErrorMsg("密码长度在6到10位之间，包括6,10");
        }
        if (StringUtils.isBlank(role)) {
            return page.setErrorMsg("角色不能为空");
        }
        if (StringUtils.isBlank(telphone)) {
            return page.setErrorMsg("请输入手机号");
        }
        if (!telphone.matches("1([\\d]{10})")) {
            return page.setErrorMsg("手机号格式不正确");
        }
        String roleId = req.getParameter("roleId");
        user.setRoleId(Long.parseLong(roleId));
        user.setId(id);
        user.setEmail(email);
        user.setPassword(password);
        user.setRole(role);
        user.setTelphone(telphone);
        try {
            if (userService.updateUser(user)) {
                return page.setSuccessMsg("更新成功");
            } else {
                return page.setErrorMsg("更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOG.error(e.getMessage(), e);
            return page.setErrorMsg("更新过程中发生异常，异常信息为：" + e.getMessage());
        }
    }

    @RequestMapping(value = "/user/find", method = RequestMethod.GET)
    public ModelAndView queryGet(ModelAndView mav) {
        List<Role> roleList = roleService.getAllRoles();
        mav.addObject("roleList", roleList);
        mav.setViewName("authority/user/find");
        return mav;
    }

    @RequestMapping(value = "/user/find", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage queryPost(HttpServletRequest req) {
        String email = req.getParameter("email");
        String pageNumStr = req.getParameter("pageNum");
        int pageNum = Constants.DEFAULT_PAGE_NUM;
        if (!StringUtils.isBlank(pageNumStr)) {
            pageNum = Integer.parseInt(pageNumStr.trim());
        }
        String pageSizeStr = req.getParameter("pageSize");
        int pageSize = Constants.DEFAULT_PAGE_SIZE;
        if (!StringUtils.isBlank(pageSizeStr)) {
            pageSize = Integer.parseInt(pageSizeStr.trim());
        }
        ResponsePage page = new ResponsePage();
        try {
            Page<User> users = null;
            User user = null;
            if (StringUtils.isBlank(email)) {
                users = userService.findAllUser(pageNum, pageSize);
                return page.setPage(users, "查询成功");
            } else {
                user = userService.findUser(email.trim());
                users = new Page<User>();
                users.add(user);
                users.setTotal(1);
                if (user != null) {
                    return page.setPage(users, "查询成功");
                }
                return page.setSuccessMsg("暂无数据");
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return page.setErrorMsg("查询过程中出现异常，异常信息为：" + e.getMessage());
        }
    }

    @RequestMapping(value = "/ajaxGetAllRoles", method = RequestMethod.POST)
    @ResponseBody
    public Object ajaxGetAllRoles() {
        List<Role> list = roleService.getAllRoles();
        return list;
    }

    @RequestMapping(value = "/getUserSql", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage getUserSql(ResponsePage page, HttpServletRequest request, @RequestParam("id") long id) {
        int pageNum = getPageNum();
        int pageSize = getPageSize();
        Map<String, Object> param = new HashMap<String, Object>();
        try {
            User user = userService.findUserById(id);
            param.put("userEmail", user.getEmail());
            Page<GUserFrequentlySql> frequentlySqls = sqlHandleService.getUserFrequentlySqlByParam(pageNum,
                pageSize,
                param);
            if (frequentlySqls == null) {
                page.setSuccessMsg(FIND_SUCCESS);
            } else {
                page.setPage(frequentlySqls, FIND_SUCCESS);
            }
        } catch (UserServiceException e) {
            LOG.error(e.getMessage());
        }

        return page;
    }
}
